package br.com.portalecbahia;

import java.util.ArrayList;
import java.util.List;

import com.google.analytics.tracking.android.EasyTracker;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import br.com.portalecbahia.connectionservices.SynchronizeAudio;
import br.com.portalecbahia.connectionservices.SynchronizeMedia;
import br.com.portalecbahia.customize.AudioListAdapter;
import br.com.portalecbahia.customize.PullToRefreshListView;
import br.com.portalecbahia.customize.PullToRefreshListView.OnRefreshListener;
import br.com.portalecbahia.customize.VideoListAdapter;
import br.com.portalecbahia.dao.MediaDAO;
import br.com.portalecbahia.listner.MediaListeners;
import br.com.portalecbahia.listner.OnCompleateAudio;
import br.com.portalecbahia.model.Media;
import br.com.portalecbahia.model.TypeMedia;
import br.com.portalecbahia.util.PortalECBahiaUtil;

public class MediaActivity  extends ListActivity implements MediaListeners, OnCompleateAudio{
	
	private Context context;
	private List<Media> lMedia;
	private ListAdapter adapterListMedia;
	private SynchronizeMedia taskMedia;
	private TypeMedia currentType ;
	private Button videoBTN;
	private Button audioBTN;
	private ImageView signalIMG;
	private Intent serviceAudio;
	private ImageView updateIMG;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.media);
        context = this;
         EasyTracker.getInstance().setContext(this);
        videoBTN = (Button) findViewById(R.id.videoBTN);
        audioBTN = (Button) findViewById(R.id.audioBTN);
        updateIMG = (ImageView) findViewById(R.id.updateIMG);

        ((PullToRefreshListView) getListView()).setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
            	if(PortalECBahiaUtil.haveNetworkConnection(context)){
            		taskMedia = new SynchronizeMedia(context);
            		taskMedia.execute();
            	}else{
        			Toast.makeText(context, getString(R.string.internetOff), Toast.LENGTH_LONG).show();
        			  ((PullToRefreshListView) getListView()).onRefreshComplete();
            	}
            }
        });
        currentType = new TypeMedia();
        currentType.setId(2l);
        listMedia();
        updateList(new View(this));
       

    }
    
    @Override
    public void onStart() {
      super.onStart();
      EasyTracker.getInstance().activityStart(this); // Add this method.
    }

    @Override
    public void onStop() {
      super.onStop();
      EasyTracker.getInstance().activityStop(this); // Add this method.
    }

	@Override
	public void onSynchronizeMediaComplete(Boolean response) {
		if(response){
			listMedia();
			
		}else{
			Toast.makeText(context, getString(R.string.serverProblem), Toast.LENGTH_LONG).show();
		}
		
	    ((PullToRefreshListView) getListView()).onRefreshComplete();
	    updateIMG.clearAnimation();

		
	}
	
	public void updateList(View view){
		if(PortalECBahiaUtil.haveNetworkConnection(context)){
			taskMedia = new SynchronizeMedia(context);
			taskMedia.execute();
			animateUpdate();
    	}else{
			Toast.makeText(context, getString(R.string.internetOff), Toast.LENGTH_LONG).show();
			  ((PullToRefreshListView) getListView()).onRefreshComplete();
    	}

	}

	private void animateUpdate() {
		int   currentRotation = 0;
		RotateAnimation anim = new RotateAnimation(currentRotation, (360*4),
		Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,0.5f);
		currentRotation = (currentRotation + 45) % 360;
		anim.setInterpolator(new LinearInterpolator());
		anim.setDuration(4000);
		anim.setRepeatMode(Animation.INFINITE);
		anim.setRepeatCount(Animation.INFINITE);
		anim.setFillEnabled(true);
		anim.setFillAfter(true);
		updateIMG.startAnimation(anim);
		
	}
	private void listMedia() {
	   	lMedia = new ArrayList<Media>();
    	lMedia.clear();
    	
    	
    	//type Video
    	if(currentType.getId() == 2){
        	lMedia = new MediaDAO(this).findAllVideo();   
        	int sizeList = lMedia.size();
        	if(lMedia.size()<10){    		
        		for (int i = 0; i < PortalECBahiaUtil.minimumListSize-sizeList; i++) {
        			lMedia.add(new Media());
    			}
        	}
        	audioBTN.setBackgroundResource(R.drawable.right_bluebtn_selected);
        	audioBTN.setTextColor(getResources().getColor(R.color.gray));
        	
        	videoBTN.setBackgroundResource(R.drawable.left_bluebtn);
        	videoBTN.setTextColor(getResources().getColor(R.color.white));
        	
        	adapterListMedia = (ListAdapter) new VideoListAdapter(this, lMedia);
		}else{
			lMedia = new MediaDAO(this).findAllAudio();
			int sizeList = lMedia.size();
	    	if(lMedia.size()<10){    		
	    		for (int i = 0; i < PortalECBahiaUtil.minimumListSize-sizeList; i++) {
	    			lMedia.add(new Media());
				}
	    	}
	      
	    	audioBTN.setBackgroundResource(R.drawable.right_bluebtn);
        	audioBTN.setTextColor(getResources().getColor(R.color.white));
        	
        	videoBTN.setBackgroundResource(R.drawable.left_bluebtn_selected);
        	videoBTN.setTextColor(getResources().getColor(R.color.gray));
        	        	
			adapterListMedia = (ListAdapter) new AudioListAdapter(this, lMedia);
		}
	    setListAdapter(adapterListMedia);
	  
	}
	
	public void listVideo(View view){
		currentType.setId(2l);
		listMedia();
	}
	
	public void listAudio(View view){
		currentType.setId(1l);

		listMedia();
	}


	public void play(View view){
		String url = (((Button)view).getContentDescription()).toString();
		if("".equals(PortalECBahiaUtil.AUDIO_PLAYING)){
			
			PortalECBahiaUtil.AUDIO_PLAYING = url;
			 
			
			serviceAudio = new Intent(this, SynchronizeAudio.class);
			SynchronizeAudio.listeners = this;
			startService(serviceAudio);

			signalIMG =  (ImageView)((RelativeLayout)view.getParent().getParent().getParent()).getChildAt(2);
			signalIMG.setImageResource(R.drawable.signal_1);
		}
	}
	public void stop(View view){
		String url = (((Button)view).getContentDescription()).toString();
		if(!"".equals(PortalECBahiaUtil.AUDIO_PLAYING) && PortalECBahiaUtil.AUDIO_PLAYING.equals(url)){
			stopService(serviceAudio); 
			
		}

	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) { 
		super.onListItemClick(l, v, position, id);
			
		   Media mediaSelectedFromList = (Media) (adapterListMedia.getItem(position-1));
		   
		   if(mediaSelectedFromList!=null  && mediaSelectedFromList.getType()!=null && mediaSelectedFromList.getType().getId() == 2)
			   startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(mediaSelectedFromList.getUrlMedia())));
		return;
	}

	@Override
	public void onCompleateAudio() {
		PortalECBahiaUtil.AUDIO_PLAYING = "";
		signalIMG.setImageResource(R.drawable.signal_2);
	}
    
}
